<?php

namespace App\Repositories;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

abstract class BaseRepository implements RepositoryInterface
{
    /**
     * @var Model $model
     */
    protected Model $model;

    /**
     * 通过构造函数注入模型
     * @param Model $model
     */
    public function __construct(Model $model)
    {
        $this->model = $model;
    }

    /**
     * 根据ID获取模型
     * @param mixed $id
     * @return Model|null
     */
    public function getById($id): ?Model
    {
        return $this->query()->find($id);
    }

    /**
     * 获取查询构建器
     * @return Builder
     */
    protected function query(): Builder
    {
        return $this->model->newQuery();
    }

    /**
     * 创建模型
     * @param array $attributes
     * @return Model
     */
    public function create(array $attributes): Model
    {
        return $this->query()->create($attributes);
    }
}
